package com.neusoft.springdemo.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.core.convert.converter.Converter;

/**
 * 定制的类型转换器，支持4种时间格式
 * 
 * @author chens
 *
 */
public class DateConverter implements Converter<String, Date> {
	private Logger logger = Logger.getLogger(DateConverter.class);

	@Override
	public Date convert(String source) {
		Date date = null;
		String pattern = "yyyy-MM-dd HH:mm:ss";
		logger.info("============================  ");
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);

		try {
			date = sdf.parse(source);
		} catch (ParseException e) {
			logger.info("=1 "+pattern);
			pattern = "yyyy-MM-dd";
			sdf.applyPattern(pattern);
			try {
				date = sdf.parse(source);
			} catch (ParseException e1) {
				logger.info("=2 "+pattern);
				pattern = "yyyy/MM/dd HH:mm:ss";
				sdf.applyPattern(pattern);
				try {
					date = sdf.parse(source);
				} catch (ParseException e2) {
					logger.info("=3 "+pattern);
					pattern = "yyyy/MM/dd";
					sdf.applyPattern(pattern);
					try {
						date = sdf.parse(source);
					} catch (ParseException e3) {
						logger.info("=4 "+pattern);
						try {
							date = sdf.parse("1970/01/01");
						} catch (ParseException e4) {

						}
					}
				}
			}

		}

		return date;
	}

}
